from django.db import DatabaseError
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListCreateAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.views import APIView
from .models import BookInfo
from .serializers import BookInfoSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ViewSetMixin,ViewSet,GenericViewSet
from .serializers import BookInfoModelSerializer,BookInfoModelSerializer2


# # class BookInfoView(APIView):
# class BookInfoView(ListModelMixin, CreateModelMixin,):
#     def get(self, request):
#         # """
#         # :param request: DRF的request对象
#         # :return:
#         # """
#         # # 1.数据库查询
#         # books = BookInfo.objects.all()
#         # # 2.序列化器转化数据格式
#         # ser = BookInfoSerializer(books, many=True)
#         # # 返回，响应数据
#         # return Response(ser.data, status=status.HTTP_400_BAD_REQUEST)
#         return self.list(request)
#
#     def post(self, request):
#         # book = request.data
#         # ser = BookInfoSerializer(data=book)
#         # ser.is_valid(raise_exception=True)
#         # ser.save()
#         # return Response(ser.data)
#         return self.create(request)


# 此处代码与上面是继承关系，封装好了上面代码的功能，简化代码
class BookInfoView(ListCreateAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer


# class BookDetailView(GenericAPIView):
#     def get(self, request, pk):
#         # # book = BookInfo.objects.get(id=pk)
#         # book = self.get_objects()
#         # # ser = BookInfoSerializer(book)
#         # ser = self.get_serializer(book)
#         # return Response(ser.data)
#         return self.retrieve(request)


class BookDetailView(RetrieveAPIView):
    """
    retrieve:
    返回图书详情数据
    """
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer


class MyPermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        return False


# 自定义Pagination类
class StandardPageNumberPagination(LimitOffsetPagination):
    page_size_query_param = 'page_size'  # 页数查询参数，即关键字名字
    max_page_size = 10
    # pass


class BookInfoViewSet(ViewSet):
    """
    list:
    返回图书列表数据

    retrieve:
    返回图书详情数据

    latest：
    返回最新的图书数据

    read:
    修改图书的阅读量
    """
    # 认证的配置
    authentication_classes = [BasicAuthentication, SessionAuthentication]

    # 权限的配置
    permission_classes = [IsAuthenticated, MyPermission]

    # 过滤-字段
    filter_fields = ('btitle', 'bread')

    # 排序配置
    filter_backend = [OrderingFilter]  # 过滤的后端
    ordering_fields = ['id', 'bread']  # 排序的字段

    # 分页
    # 自定义Pagination类，为视图添加不同分页行为
    # pagination_class = StandardPageNumberPagination

    # 游标分页，偏移
    pagination_class = LimitOffsetPagination

    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    @action(methods=['get'], detail=False)
    def latest(self, request):
        """最近添加的书籍"""
        book = BookInfo.objects.latest('id')
        ser = self.get_serializer(book)
        raise DatabaseError()
        return Response(ser.data)

    @action(methods=['put'], detail=True)
    def read(self,request, pk):
        """更新书籍"""
        data = request.data
        book = self.get_object()
        ser = self.get_serializer(book, data = data)
        ser.is_valid(raise_exception=True)

        ser.save()
        return Response(ser.data)


class BookDetailView2(RetrieveAPIView):
    """
    retrieve:
    返回图书详情数据
    """

    queryset = BookInfo.objects.all()

    def get_serializer_class(self):
        if self.request.version == '1.0':
            return BookInfoModelSerializer
        else:
            return BookInfoModelSerializer2

